package com.bridge.common.utils;


import com.alibaba.fastjson.JSONObject;
import com.bridge.common.consts.Const;
import com.bridge.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

@Slf4j
public final class HttpTookit {


    public static String httpsGe1t(String url, Map<String, String> params, Map<String, String> header) throws Exception {
        String result="{\n" +
                "    \"message\": \"SUCCESS\",\n" +
                "    \"data\": {\n" +
                "        \"userID\": 11616,\n" +
                "        \"upid\": 173240,\n" +
                "        \"date\": \"2023-05-17 10:16:48\",\n" +
                "        \"countx\": 125,\n" +
                "        \"width\": 600,\n" +
                "        \"height\": 450,\n" +
                "        \"result\": \"[['pipe', [183, 278], [195, 290]], ['pipe', [179, 266], [192, 278]], ['pipe', [193, 284], [205, 295]], ['pipe', [195, 275], [207, 286]], ['pipe', [170, 244], [182, 255]], ['pipe', [181, 257], [192, 268]], ['pipe', [182, 225], [192, 237]], ['pipe', [171, 255], [182, 266]], ['pipe', [131, 348], [143, 360]], ['pipe', [127, 338], [140, 350]], ['pipe', [138, 371], [150, 383]], ['pipe', [126, 371], [139, 383]], ['pipe', [136, 360], [148, 372]], ['pipe', [308, 300], [322, 313]], ['pipe', [110, 326], [123, 338]], ['pipe', [191, 228], [202, 239]], ['pipe', [122, 359], [135, 371]], ['pipe', [366, 262], [377, 273]], ['pipe', [280, 317], [291, 328]], ['pipe', [372, 272], [383, 283]], ['pipe', [260, 333], [273, 344]], ['pipe', [146, 352], [158, 363]], ['pipe', [116, 336], [128, 348]], ['pipe', [356, 255], [367, 266]], ['pipe', [147, 363], [160, 375]], ['pipe', [195, 255], [206, 267]], ['pipe', [579, 134], [591, 146]], ['pipe', [96, 423], [107, 435]], ['pipe', [118, 348], [131, 361]], ['pipe', [103, 339], [115, 351]], ['pipe', [190, 318], [203, 330]], ['pipe', [84, 418], [96, 430]], ['pipe', [150, 340], [162, 352]], ['pipe', [392, 274], [404, 285]], ['pipe', [295, 304], [306, 315]], ['pipe', [205, 293], [217, 304]], ['pipe', [227, 303], [240, 315]], ['pipe', [122, 384], [134, 396]], ['pipe', [183, 237], [194, 248]], ['pipe', [106, 348], [120, 360]], ['pipe', [92, 385], [104, 397]], ['pipe', [167, 353], [181, 366]], ['pipe', [139, 342], [151, 354]], ['pipe', [554, 129], [566, 142]], ['pipe', [342, 261], [355, 272]], ['pipe', [354, 286], [366, 296]], ['pipe', [102, 379], [115, 391]], ['pipe', [149, 376], [161, 390]], ['pipe', [400, 270], [412, 282]], ['pipe', [543, 141], [555, 153]], ['pipe', [111, 384], [123, 396]], ['pipe', [300, 313], [312, 324]], ['pipe', [335, 320], [348, 332]], ['pipe', [182, 247], [193, 258]], ['pipe', [237, 284], [250, 295]], ['pipe', [576, 122], [585, 134]], ['pipe', [551, 153], [564, 165]], ['pipe', [326, 240], [336, 250]], ['pipe', [179, 318], [191, 330]], ['pipe', [565, 153], [579, 166]], ['pipe', [291, 314], [301, 324]], ['pipe', [342, 273], [355, 284]], ['pipe', [264, 317], [276, 328]], ['pipe', [158, 346], [170, 359]], ['pipe', [160, 332], [173, 344]], ['pipe', [327, 259], [338, 270]], ['pipe', [203, 224], [214, 236]], ['pipe', [272, 331], [283, 342]], ['pipe', [239, 294], [251, 305]], ['pipe', [280, 297], [291, 308]], ['pipe', [215, 296], [227, 308]], ['pipe', [280, 308], [291, 319]], ['pipe', [566, 145], [578, 157]], ['pipe', [542, 156], [554, 169]], ['pipe', [308, 331], [321, 343]], ['pipe', [392, 246], [402, 257]], ['pipe', [158, 358], [170, 370]], ['pipe', [254, 271], [266, 283]], ['pipe', [565, 132], [576, 144]], ['pipe', [230, 275], [242, 285]], ['pipe', [173, 330], [185, 342]], ['pipe', [226, 284], [238, 295]], ['pipe', [204, 282], [216, 293]], ['pipe', [370, 246], [382, 258]], ['pipe', [148, 390], [160, 402]], ['pipe', [378, 261], [390, 272]], ['pipe', [552, 169], [565, 181]], ['pipe', [530, 155], [542, 168]], ['pipe', [337, 235], [348, 246]], ['pipe', [138, 383], [149, 395]], ['pipe', [205, 273], [217, 284]], ['pipe', [333, 246], [344, 258]], ['pipe', [555, 140], [567, 153]], ['pipe', [323, 273], [335, 284]], ['pipe', [585, 166], [596, 179]], ['pipe', [425, 321], [436, 331]], ['pipe', [135, 329], [148, 340]], ['pipe', [304, 259], [315, 270]], ['pipe', [202, 237], [214, 248]], ['pipe', [345, 301], [357, 312]], ['pipe', [315, 239], [325, 250]], ['pipe', [73, 407], [85, 419]], ['pipe', [217, 284], [228, 295]], ['pipe', [254, 278], [266, 289]], ['pipe', [348, 231], [360, 243]], ['pipe', [159, 371], [172, 384]], ['pipe', [412, 303], [424, 315]], ['pipe', [399, 316], [411, 328]], ['pipe', [207, 256], [219, 267]], ['pipe', [325, 303], [338, 316]], ['pipe', [539, 167], [551, 179]], ['pipe', [310, 272], [321, 283]], ['pipe', [383, 270], [394, 281]], ['pipe', [414, 321], [425, 331]], ['pipe', [460, 314], [472, 325]], ['pipe', [122, 329], [134, 340]], ['pipe', [313, 321], [325, 333]], ['pipe', [193, 250], [206, 261]], ['pipe', [220, 233], [232, 244]], ['pipe', [128, 430], [141, 442]], ['pipe', [221, 272], [232, 283]], ['pipe', [72, 418], [85, 429]], ['pipe', [578, 188], [588, 200]], ['pipe', [365, 281], [377, 292]], ['pipe', [360, 303], [372, 314]]]\",\n" +
                "        \"radius\": 4,\n" +
                "        \"flag\": 1,\n" +
                "        \"record\": 0,\n" +
                "        \"count\": 125,\n" +
                "        \"recordID\": 174904,\n" +
                "        \"srcURL\": \"95f6019e-2564-46c6-83a3-0b6d46960091.png\",\n" +
                "        \"recordURL\": \"95f6019e-2564-46c6-83a3-0b6d46960091.png\"\n" +
                "    },\n" +
                "    \"hr\": 200\n" +
                "}";
//        System.out.println(result);
        return result;
    }

//    public static void main(String[] args) throws Exception {
//        httpsGe1t(null,null,null);
//    }

    public static String httpsGet(String url, Map<String, String> params, Map<String, String> header) throws Exception {
        if(params!=null){
            Set<String> keys= params.keySet();
            for (String queryString:keys){
                if (-1 == url.indexOf("?")) {
                    url += "?" + queryString+"="+params.get(queryString);
                } else {
                    url += "&" + queryString+"="+params.get(queryString);
                }
            }
        }

        URIBuilder ub = new URIBuilder(url);
        URL url1 = ub.build().toURL();
        //初始化HttpClient
        BasicCookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
                .build();
        //创建HttpGet
        HttpGet httpGet = new HttpGet(url1.toString());
        //设置header
        if (header != null) {
            Set<String> keySet = header.keySet();
            for (String key : keySet) {
                httpGet.setHeader(key, header.get(key));
            }
        }

        HttpClientContext context = HttpClientContext.create();
        //发起请求，获取response对象
        CloseableHttpResponse response = httpClient.execute(httpGet,context);
        //获取请求状态码

        //获取返回数据实体对象
        HttpEntity entity = response.getEntity();

        //转为字符串
        String result = EntityUtils.toString(entity,"UTF-8");
        return result;
    }



    private static String doTryGet(String url, Map<String,Object> queryMap, Map<String, String> headMap) throws Exception {
        if(queryMap!=null){
            Set<String> keys= queryMap.keySet();
            for (String queryString:keys){
                if (-1 == url.indexOf("?")) {
                    url += "?" + queryString+"="+queryMap.get(queryString);
                } else {
                    url += "&" + queryString+"="+queryMap.get(queryString);
                }
            }
        }
        HttpGet httpGet = new HttpGet(url);

        if (headMap != null) {
            for (String key : headMap.keySet()) {
                httpGet.addHeader(key, headMap.get(key));
            }
        }

        return HttpClientUtil.doHttpRequest(httpGet, "utf-8");


    }

    private static String doTryGet(String url, String queryString, Map<String, String> headMap) throws Exception {

        if (queryString != null && !"".equals(queryString))
            if (-1 == url.indexOf("?")) {
                url += "?" + queryString;
            } else {
                url += "&" + queryString;
            }


        HttpGet httpGet = new HttpGet(url);

        if (headMap != null) {
            for (Map.Entry<String, String> entry : headMap.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());


            }

        }

        return HttpClientUtil.doHttpRequest(httpGet, "utf-8");


    }

    public static String doGetHeadMap(String url, String queryString, Map<String, String> headMap) {

        int tryCount = Const.TRY_MAX_COUNT;
        while (tryCount-- > 0) {
            try {
                return doTryGet(url, queryString, headMap);
            } catch (Exception e) {
                log.error("执行HTTP Get请求" + url + "时，发生异常！", e);
            }
        }

        return "";


    }

    public static String doGet(String url, String queryString) {

        int tryCount = Const.TRY_MAX_COUNT;
        while (tryCount-- > 0) {
            try {
                return doTryGet(url, queryString, null);
            } catch (Exception e) {
                log.error("执行HTTP Get请求" + url + "时，发生异常！", e);
            }
        }

        return "";
    }

    public static String doGet(String url, Object object, Map<String, String> headMap) {
        Map<String,Object> map=new HashMap<String,Object>();
        if(object != null){
            map=JSONObject.parseObject(JSONObject.toJSONString(object)).getInnerMap();
        }

        int tryCount = Const.TRY_MAX_COUNT;
        while (tryCount-- > 0) {
            try {
                return doTryGet(url, map, headMap);
            } catch (Exception e) {
                log.error("执行HTTP Get请求" + url + "时，发生异常！", e);
            }
        }

        return "";
    }


    public static String doPostJson(String strURL, String paramsJson) {
        int tryCount = Const.TRY_MAX_COUNT;


        while (tryCount-- > 0) {
            try {
                return doTryPostJson(strURL, paramsJson);

            } catch (Exception e) {
                log.error("执行HTTP Post json请求" + strURL + "时，发生异常！", e);

            }
        }


        return "";

    }

    public static String doPostJson(String strURL, Object paramsJson) {
        return doPostJson(strURL,JSONObject.toJSONString(paramsJson));
    }

    /**
     * MultipartFile转File
     * <p>
     * 项目根路径创建临时文件，转换得到File，再删除临时文件
     *
     * @param multipartFile
     * @return
     */
    public static File multiPartFileToFile(MultipartFile multipartFile) throws IOException {

        //获取文件名
        String originalFilename = multipartFile.getOriginalFilename();

        //获取默认定位到的当前用户目录("user.dir"),也就是当前应用的根路径
        String tempDir = System.getProperty("user.dir");

        //根目录下生成临时文件
        File file = new File(tempDir+File.separator+originalFilename);

        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);

        return file;
    }

    private static String doTryPostJson(String strURL, String paramsJson) throws Exception {

        HttpURLConnection connection = null;
        try {
            URL url = new URL(strURL);// 创建连接
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            //  connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), "utf-8"); // utf-8编码
            out.append(paramsJson);
            out.flush();
            out.close();
            InputStream is = connection.getInputStream();
            // 读取请求内容
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            return URLDecoder.decode(sb.toString(), "utf-8");

        } catch (IOException e) {
            throw e;

        } finally {
            try {
                connection.disconnect();
            } catch (Exception e) {

            }
        }
        // return ""; // 自定义错误信息*/


    }


    /**
     * @param url
     * @param params
     * @param code
     * @return
     */
    public static String doPost(String url, Map<String, String> params, String code) {

        int tryCount = Const.TRY_MAX_COUNT;

        while (tryCount-- > 0) {
            try {
                return doTryPost(url, params, code, null);
            } catch (Exception e) {
                log.error("执行HTTP Post请求" + url + "时，发生异常！", e);
            }


        }

        return "";


    }

    /**
     * @param url
     * @param params
     * @param code
     * @return
     */
    private static String doTryPost(String url, Map<String, String> params, String code, Map<String, String> headMap) throws Exception {


        return HttpClientUtil.doHttpRequest(url, params, code, headMap);


    }


    /**
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map<String, String> params) {

        return doPost(url, params, "utf-8");

      /*  com.sk.webCommon.util.https.http.HttpClient client = new com.sk.webCommon.util.https.http.HttpClient();

        PostParameter[] pps =null;

        if(params!=null ){
            pps = new PostParameter[params.size()];
            Iterator iter = params.entrySet().iterator();
            int i = 0;
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                PostParameter pp = new PostParameter((String) entry.getKey(), (String) entry.getValue());
                pps[i] = pp;
                i++;
            }
        }

//		method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        Response response = null;




        try {
            response = client.post(url, pps, false, null);
            return response.asString();
        } catch (Exception e) {
            log.error("执行HTTP Post请求" + url + "时，发生异常！", e);
        } finally {
//			method.releaseConnection();
        }*/

        //   return "";
    }

//    public static void main(String[] args) throws UnsupportedEncodingException {

//		String url="http://yzm.mb345.com/ws/BatchSend2.aspx";
//		Map<String, String> params =new HashMap<String, String>();
//		params.put("CorpID", "CDLK00064");
//		params.put("Pwd", "00064@");
//		params.put("Mobile", "15990084484");
//
//		params.put("Content",EncodeUtil.encodeStr("您正在绑定银行帐号，手机验证码:803617，有效期120秒，客服热线4008805740。【泓信在线】"));
//


//    }


    public static String sendGet(String url) {


        HttpGet getMethod = new HttpGet(url);


        getMethod.setHeader("Content-type",
                "text/html;charset=utf-8");
        try {

            return HttpClientUtil.doHttpRequest(getMethod, "utf-8");
        } catch (Exception e) {


        }

        return null;

       /* String msg = "";
        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(
                    url).openConnection();
            msg = creatConnection(url, httpURLConnection);
        } catch (IOException io) {
            log.error("http close" + io);
        }
        return msg;*/
    }

    private static String creatConnection(String url,
                                          HttpURLConnection httpURLConnection) {
        String msg = "";
        try {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
            httpURLConnection = (HttpURLConnection) new URL(url)
                    .openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setRequestProperty("Content-Type", "text/html;charset=utf-8");
            msg = receiveMessage(httpURLConnection);
        } catch (IOException io) {
            io.printStackTrace();
            log.error("Http Connect to :" + url + " " + "IOFail!");
        } catch (Exception ex) {
            log.error("Http Connect to :" + url + " " + "Failed" + ex);
        } finally {
            closeConnection(httpURLConnection);
        }
        return msg;
    }

    private static void closeConnection(HttpURLConnection httpURLConnection) {
        try {
            if (httpURLConnection != null)
                httpURLConnection.disconnect();
        } catch (Exception localException) {
        }
    }

    private static String receiveMessage(HttpURLConnection httpURLConnection) {
        String responseBody = null;
        try {
            InputStream httpIn = httpURLConnection.getInputStream();
            if (httpIn != null) {
                ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
                byte tempByte;
                while (-1 != (tempByte = (byte) httpIn.read())) {
                    byte tempByte1 = 0;
                    byteOut.write(tempByte1);
                }
                responseBody = new String(byteOut.toByteArray(), "utf-8");
            }
        } catch (IOException ioe) {
            log.error("Http Connect tosss :" + ioe.getLocalizedMessage() + " "
                    + "IOEFail!");
            return null;
        }
        return responseBody;
    }

    public static String getRealIpAddr(HttpServletRequest request) {
        try {

            String ip = getIpAddr(request);
            return ip;


            /*String ip = request.getHeader("X-Real-IP");


            if ((ip == null) || (ip.length() == 0)
                    || ("unknown".equalsIgnoreCase(ip))) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if ((ip == null) || (ip.length() == 0)
                    || ("unknown".equalsIgnoreCase(ip))) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if ((ip == null) || (ip.length() == 0)
                    || ("unknown".equalsIgnoreCase(ip))) {
                ip = request.getRemoteAddr();
            }
            return ip;*/
        } catch (Exception e) {

            e.printStackTrace();
            return getHostAddress();
        }


    }

    public static String getHostAddress() {
        try {
            InetAddress ipaddr = InetAddress.getLocalHost();
            return ipaddr.getHostAddress();

        } catch (Exception e) {
            // TODO: handle exception
        }
        return "127.0.0.1";

    }


    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (ip != null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (ip != null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }


    public static String getPath(HttpServletRequest request) {
        String path = request.getContextPath();
        return request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort() + path + "/";
    }


    /**
     * 发送json包
     *
     * @param url
     * @param param json字符串
     * @return
     * @throws Exception
     */
    public static String sendPostFromJson(String url, String param) throws Exception {


        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            new Exception("发送 POST 请求出现异常！" + e);

        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;


    }


    /**
     * 通过httpClient上传文件
     * @param fileName
     * @param path
     * @return 外部域名的下载url
     */
    public static String filePost( String url,File file,Map<String, String> params,Map<String, String> headMap) {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse  response = null;
        InputStream content = null;
        BufferedReader in = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            //HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            if(headMap!=null){
                Set<String> keys= headMap.keySet();
                for (String queryString:keys){
                    httpPost.addHeader(queryString, headMap.get(queryString));//其余参数，可自定义
                }
            }
            String[] fileName=file.getName().split("\\.");
            builder.addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, fileName[0]+"/"+fileName[1]);// 文件流
            if(params!=null){
                Set<String> keys= params.keySet();
                for (String queryString:keys){
                    if(StringUtils.isNotEmpty(params.get(queryString))){
                        builder.addTextBody(queryString, params.get(queryString));//其余参数，可自定义
                    }
                }
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();//接收调用外部接口返回的内容
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                // 返回的内容都在content中
                content = responseEntity.getContent();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                if(!StringUtils.isBlank(result)) {
                    log.info("上传文件"+file.getName()+"返回参数==>"+result);
                }else {
                    log.error("上传文件失败：返回result为null");
                }

            }
        }catch(Exception e) {
            log.error("上传文件失败：",e);
        }finally {//处理结束后关闭httpclient的链接
            try {
                if (response != null)
                    response.close();
                if (httpClient != null)
                    httpClient.close();
                if (content != null)
                    content.close();
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }


    public static String postBodyParam( String url,Map<String, Object> params,Map<String, String> headMap) {
        if(params==null){
            params=new HashMap<>();
        }
        if(headMap==null){
            headMap=new HashMap<>();
        }
        if(!headMap.containsKey("Content-Type")){
            headMap.put("Content-Type","application/json");
        }
        try(CloseableHttpClient httpClient=HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            JSONObject json = new JSONObject();
            if(params!=null) {
                Set<String> keys = params.keySet();
                for (String queryString : keys) {
                    if (Objects.nonNull(params.get(queryString))) {
                        json.put(queryString, params.get(queryString));
                    }
                }
            }
            String paramJson=json.toJSONString();
            StringEntity stringEntity =new StringEntity(paramJson,"UTF-8");
            httpPost.setEntity(stringEntity);

            Set<String> keys= headMap.keySet();
            for (String queryString:keys){
                httpPost.addHeader(queryString, headMap.get(queryString));//其余参数，可自定义
            }
            RequestConfig build = RequestConfig.custom()
                    .setConnectTimeout(120000)
                    .setSocketTimeout(600000)
                    .setConnectionRequestTimeout(120000)
                    .build();
            httpPost.setConfig(build);
            log.info("postBodyParam 开始请求,url:{}, param:{}",url,paramJson);

            HttpResponse response = httpClient.execute(httpPost);
            String result = EntityUtils.toString(response.getEntity());
            log.info("postBodyParam 请求完成,url:{}, result:{}",url,result);
            return result;
        }catch (Exception e){

            log.error("postBodyParam 请求异常,url:{}, e ==>",url,e);
            if(e instanceof SocketException){
                throw new ServiceException("连接异常："+e.getMessage());
            }
            return null;
        }
    }


}
